package com.hm.common.conversion;

/**
 * @author shishun.wang
 * @date 2018年5月7日 下午3:07:08
 * @version 1.0
 * @describe
 */
public class U16 {

	private String hex;

	public U16(String hex) {
		this.hex = hex;
	}

	/**
	 * 16进制转ASCII
	 * 
	 * @return
	 */
	public String toAscii() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < hex.length() - 1; i += 2) {
			String output = hex.substring(i, (i + 2));
			int decimal = Integer.parseInt(output, 16);
			sb.append((char) decimal);
		}
		return sb.toString();
	}

	/**
	 * 十六进制字符串转十进制
	 * 
	 * @return
	 */
	public int toU10() {
		String hexTmp = hex.toUpperCase();
		int max = hexTmp.length();
		int result = 0;
		for (int i = max; i > 0; i--) {
			char c = hexTmp.charAt(i - 1);
			int algorism = 0;
			if (c >= '0' && c <= '9') {
				algorism = c - '0';
			} else {
				algorism = c - 55;
			}
			result += Math.pow(16, max - i) * algorism;
		}
		return result;
	}

	/**
	 * 十六转二进制
	 * 
	 * @return 二进制字符串
	 */
	public String toU2() {
		String hexTmp = hex.toUpperCase();
		String result = "";
		int max = hexTmp.length();
		for (int i = 0; i < max; i++) {
			char c = hexTmp.charAt(i);
			switch (c) {
			case '0':
				result += "0000";
				break;
			case '1':
				result += "0001";
				break;
			case '2':
				result += "0010";
				break;
			case '3':
				result += "0011";
				break;
			case '4':
				result += "0100";
				break;
			case '5':
				result += "0101";
				break;
			case '6':
				result += "0110";
				break;
			case '7':
				result += "0111";
				break;
			case '8':
				result += "1000";
				break;
			case '9':
				result += "1001";
				break;
			case 'A':
				result += "1010";
				break;
			case 'B':
				result += "1011";
				break;
			case 'C':
				result += "1100";
				break;
			case 'D':
				result += "1101";
				break;
			case 'E':
				result += "1110";
				break;
			case 'F':
				result += "1111";
				break;
			}
		}
		return result;
	}
}
